/**
 * @Title: BaseParaService
 * @Package cn.com.yiqi.wsc.service.base
 * @Description: TODO
 * Copyright: Copyright (c) 2016
 * Company: 成都壹柒互动科技有限公司
 * @author 会员系统组-林威
 * @date 2017/3/20 10:11
 * @version V1.0
 */
package cn.com.yiqi.wsc.service.base;

import cn.com.yiqi.wsc.dao.appparam.AppParamDao;
import cn.com.yiqi.wsc.dao.appparam.entity.AppParamEntity;

import cn.com.yiqi.wsc.service.weixin.impl.WeixinPayImpl;
import org.apache.commons.lang.time.DateUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.Date;

/**
 *
 *@ClassName: BaseParaService
 * Description: TODO
 * @author 会员系统组-林威
 * @date 2017/3/20 10:11
 *
 */
@Service
public class BaseParaService {
    @Autowired
    WeixinPayImpl weixinPay;

    @Autowired
    AppParamDao paramDao;
    static AppParamEntity ticketPara;
    static AppParamEntity tokenPara;



    /**是否过期*/
    private Boolean notExpire(Date date){
        return DateUtils.addSeconds(date,7100).after(new Date());
    }

    public String getAccesstoken(){
        if(tokenPara == null || !notExpire(tokenPara.getUpdateTime())){
            refreshToken();
        }
        return tokenPara.getValue();

    }
    public String getTicket(){
        if(ticketPara == null || !notExpire(ticketPara.getUpdateTime())){
            refreshTicket();
        }
        return ticketPara.getValue();

//        if(null == valueOperations.get(WeixinRedisKey.ticket.getValue())){
//            refreshTicket();
//        }
//        return valueOperations.get(WeixinRedisKey.ticket.getValue());
    }
    public void refreshToken(){
        tokenPara = paramDao.getByCode("WX_ACCESSTOKEN");
        if(StringUtils.isEmpty(tokenPara.getValue()) || !notExpire(tokenPara.getUpdateTime())){
            String token = weixinPay.gettoken();
            tokenPara.setValue(token);
            tokenPara.setUpdateTime(new Date());
            paramDao.update(tokenPara);
        }
    }
    public void refreshTicket(){
        ticketPara = paramDao.getByCode("WX_TIKECT");
        if(StringUtils.isEmpty(ticketPara.getValue()) || !notExpire(ticketPara.getUpdateTime())){
            String ticket = weixinPay.getTiket(getAccesstoken());
            ticketPara.setValue(ticket);
            ticketPara.setUpdateTime(new Date());
            paramDao.update(ticketPara);
        }
    }

    public String getByCode(String code){
        return paramDao.getByCode(code).getValue();
    }

    /**系统logo*/
    public String sysLoge(){
        return "/"+getByCode("SYS_LOGO");

    }
}
